package com.yonyou.gmmc.service.JDInterface.service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.marketing.common.FrameHttpUtil;
import org.marketing.common.exception.ServiceBizException;
import org.marketing.common.util.CheckUtil;
import org.marketing.common.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.infoservice.filestore.FileStore;
import com.infoservice.filestore.FileStoreException;
import com.yonyou.gmmc.service.JDInterface.constant.JDInterfaceConstant;
import com.yonyou.gmmc.service.JDInterface.dao.TmTpEnterpriseMarketingMapper;
import com.yonyou.gmmc.service.JDInterface.dao.TmTpOrderInfoMapper;
import com.yonyou.gmmc.service.JDInterface.dao.TmTpProductCategoryMapper;
import com.yonyou.gmmc.service.JDInterface.dao.TmTpProductDetailGeneralMapper;
import com.yonyou.gmmc.service.JDInterface.dao.TmTpProductDetailMapper;
import com.yonyou.gmmc.service.JDInterface.dao.TmTpProductDetailVidoMapper;
import com.yonyou.gmmc.service.JDInterface.dao.TmTpProductGroupMapper;
import com.yonyou.gmmc.service.JDInterface.dao.TmTpProductPoolMapper;
import com.yonyou.gmmc.service.JDInterface.dao.TmTpProductPoolTempMapper;
import com.yonyou.gmmc.service.JDInterface.dao.TtJdOrderVariancMapper;
import com.yonyou.gmmc.service.JDInterface.entity.ProductPoolPO;
import com.yonyou.gmmc.service.JDInterface.entity.ProductPricePO;
import com.yonyou.gmmc.service.JDInterface.entity.ProductSaleStatePO;
import com.yonyou.gmmc.service.JDInterface.entity.ProductStatePO;
import com.yonyou.gmmc.service.JDInterface.model.TmTpEnterpriseMarketing;
import com.yonyou.gmmc.service.JDInterface.model.TmTpOrderInfo;
import com.yonyou.gmmc.service.JDInterface.model.TmTpProductCategory;
import com.yonyou.gmmc.service.JDInterface.model.TmTpProductDetail;
import com.yonyou.gmmc.service.JDInterface.model.TmTpProductDetailBook;
import com.yonyou.gmmc.service.JDInterface.model.TmTpProductDetailGeneral;
import com.yonyou.gmmc.service.JDInterface.model.TmTpProductDetailVido;
import com.yonyou.gmmc.service.JDInterface.model.TmTpProductPool;
import com.yonyou.gmmc.service.JDInterface.model.TmTpProductPoolTemp;
import com.yonyou.gmmc.service.JDInterface.model.TtJdOrderVarianc;
import com.yonyou.gmmc.service.JDInterface.thread.AddBaseThread;
import com.yonyou.gmmc.service.JDInterface.thread.BaseThread;
import com.yonyou.gmmc.service.JDInterface.thread.GetJdPriceThread;
import com.yonyou.gmmc.service.JDInterface.thread.GetPriceThread;
import com.yonyou.gmmc.service.JDInterface.thread.GetSaleStateThread;
import com.yonyou.gmmc.service.JDInterface.thread.GetSellPriceThread;
import com.yonyou.gmmc.service.JDInterface.thread.GetSkuStateThread;
import com.yonyou.gmmc.service.JDInterface.thread.GetSkuThread;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

@Transactional
@Service("productService")
public class ProductService {
	private Logger logger = Logger.getLogger(ProductService.class);
	private static String pageNumUrl = "https://bizapi.jd.com/api/product/getPageNum";
	private static String skuUrl = "https://bizapi.jd.com/api/product/getSku";
	private static String detailUrl = "https://bizapi.jd.com/api/product/getDetail";
	private static String skuStateUrl = "https://bizapi.jd.com/api/product/skuState";
	private static String jdPriceUrl = "https://bizapi.jd.com/api/price/getJdPrice";
	private static String priceUrl = "https://bizapi.jd.com/api/price/getPrice";
	private static String getNewOrder = "https://bizapi.jd.com/api/checkOrder/checkNewOrder";
	private static String getDlokOrder = "https://bizapi.jd.com/api/checkOrder/checkDlokOrder";
	private static String getRefuseOrder = "https://bizapi.jd.com/api/checkOrder/checkRefuseOrder";
	private static String getSimilarSku = "https://bizapi.jd.com/api/product/getSimilarSku";
	private static String categorySku = "https://bizapi.jd.com/api/product/getCategory";
	private static String categoryUrl = "https://bizapi.jd.com/api/product/getCategorys";
	private static String saleStateUrl = "http://bizapi.jd.com/api/product/check";
	private static String sellPriceUrl = "https://bizapi.jd.com/api/price/getSellPrice";
	private static String VEDIO = "vedio";
	private static String BOOK = "book";
	@Autowired
	private TmTpProductPoolMapper productPoolMapper;
	@Autowired
	private TmTpProductDetailMapper productDetailMapper;
	@Autowired
	private TmTpProductGroupMapper productGroupMapper;
	@Autowired
	private TmTpEnterpriseMarketingMapper tmTpEnterpriseMarketingMapper;
	@Autowired
	private TmTpProductCategoryMapper productCategoryMapper;
	@Autowired
	private TmTpProductPoolTempMapper productPoolTempMapper;
	@Autowired
	private TmTpProductDetailGeneralMapper productDetailGeneralMapper;
	@Autowired
	private TmTpProductDetailVidoMapper productDetailVidoMapper;
//	@Autowired
//	private TmTpProductDetailBookMapper productDetailBookMapper;
	@Autowired
	private JDInterfaceService jdInterfaceService;
	@Autowired
	private TmTpOrderInfoMapper TmTpOrderInfoMapper;
	@Autowired
	private TtJdOrderVariancMapper jdOrderVariancMapper;

	@Value("${synchronous}")
	private boolean synchronous;
	@Value("${synchronousNum}")
	private Integer synchronousNum;
	@Value("${JdOrderDay}")
	private Integer JdOrderDay;

	/**
	 * 获取商品池编号
	 * 
	 * @author lyq
	 * @date 2017年4月11日
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public Map<String, Object> getPageNum(String token) {
		try {
			String params = "token=" + token;
			String result = FrameHttpUtil.sendPost(pageNumUrl, params);
			logger.info("ProductService.getPageNum==>result:" + result);
			JSONObject data = JSONObject.fromObject(result);
			List<ProductPoolPO> ppList = null;
			String resultCode = data.getString("resultCode");
			Map<String, Object> map = new HashMap<>();
			map.put("success", data.getString("success"));
			map.put("resultMessage", data.getString("resultMessage"));
			map.put("resultCode", resultCode);
			if (resultCode.equals(JDInterfaceConstant.RESULTCODE_0000)) {
				TmTpProductPoolTemp productPoolTemp = new TmTpProductPoolTemp();
				// 删除临时表数据
				productPoolTempMapper.delete(productPoolTemp);
				JSONArray pList = data.getJSONArray("result");
				ppList = JSONArray.toList(pList, new ProductPoolPO(), new JsonConfig());// 参数1为要转换的JSONArray数据，参数2为要转换的目标数据，即List盛装的数据
				for (ProductPoolPO po : ppList) {
					TmTpProductPoolTemp productPoolTempPo = new TmTpProductPoolTemp();
					productPoolTempPo.setName(po.getName());
					productPoolTempPo.setPageNum(po.getPage_num());
					productPoolTempPo.setCreateDate(new Date());
					productPoolTempPo.setCreateBy(JDInterfaceConstant.WX_USER_ID);
					productPoolTempPo.setStatus(JDInterfaceConstant.PRODUCT_POOL_1001);
					productPoolTempPo.setJdpriceState(JDInterfaceConstant.PRODUCT_POOL_1001);
					productPoolTempPo.setPriceState(JDInterfaceConstant.PRODUCT_POOL_1001);
					productPoolTempPo.setGoDownState(JDInterfaceConstant.PRODUCT_POOL_1001);
					productPoolTempPo.setSaleState(JDInterfaceConstant.PRODUCT_POOL_1001);
					productPoolTempPo.setSimilarState(JDInterfaceConstant.PRODUCT_POOL_1001);
					// 保存临时表数据
					productPoolTempMapper.insertSelective(productPoolTempPo);
					TmTpProductPool param = new TmTpProductPool();
					param.setPageNum(po.getPage_num());
					List<TmTpProductPool> tpProductPool = productPoolMapper.select(param);
					TmTpProductPool productPoolPo = new TmTpProductPool();
					productPoolPo.setName(po.getName());
					if (tpProductPool != null && tpProductPool.size() > 0) {
						Example example = new Example(TmTpProductPool.class);
						Criteria criteria = example.createCriteria();
						criteria.andCondition("page_num = ", po.getPage_num());
						productPoolPo.setUpdateDate(new Date());
						productPoolPo.setUpdateBy(JDInterfaceConstant.WX_USER_ID);
						long lo = productPoolMapper.updateByExampleSelective(productPoolPo, example);
						logger.info("ProductService.getPageNum==>" + po.getPage_num() + "号池更新成功，数据更改" + lo + "条。。。。");

					} else {
						productPoolPo.setCreateDate(new Date());
						productPoolPo.setCreateBy(JDInterfaceConstant.WX_USER_ID);
						productPoolPo.setPageNum(po.getPage_num());
						long lo = productPoolMapper.insertSelective(productPoolPo);
						logger.info("ProductService.getPageNum==>" + po.getPage_num() + "号池保存成功，数据更改" + lo + "条。。。。");
					}
				}
			}

			return map;
		} catch (Exception e) {
			logger.error("ProductService.getPageNum==>" + e.getMessage(), e);
			throw new ServiceBizException(e.getMessage(), e);
		}
	}

	/**
	 * 获取商品池商品
	 * 
	 * @author lyq
	 * @date 2017年4月11日
	 * @return
	 * @throws Exception
	 */
	public Map<String, Object> getSku() {
		try {
			Example example = new Example(TmTpProductPoolTemp.class);
			Criteria criteria = example.createCriteria();
			criteria.andCondition("status=", JDInterfaceConstant.PRODUCT_POOL_1001);
			example.setOrderByClause("PAGE_NUM ASC");
			List<TmTpProductPoolTemp> list = productPoolTempMapper.selectByExample(example);
			BaseThread plate = new BaseThread();
			// 生产者线程
			new Thread(new AddBaseThread(plate, list)).start();

			// 消费者线程
			for (int i = 0; i < synchronousNum; i++) {
				new Thread(new GetSkuThread(plate, this)).start();
			}

			Map<String, Object> map = new HashMap<>();
			map.put("resultCode", JDInterfaceConstant.RESULTCODE_0000);
			return map;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new ServiceBizException(e.getMessage(), e);
		}
	}

	public void querySku(Integer pool) {
		try {
			String token = jdInterfaceService.getToken();
			String param = "token=" + token + "&pageNum=" + pool;
			String result = FrameHttpUtil.sendPost(skuUrl, param);
			logger.info("ProductService.getSku==>result:" + result);
			JSONObject data = JSONObject.fromObject(result);
			String resultCode = data.getString("resultCode");
			if (resultCode.equals(JDInterfaceConstant.RESULTCODE_0000)) {
				String[] pList = data.getString("result").split(",");
				Integer i = 0;
				// String s = "3782671,4261668";
				// String[] pList = s.split(",");
				for (String sku : pList) {
					Map<String, String> params = new HashMap<String, String>();
					params.put("sku", sku);
					params.put("pageNum", pool.toString());
					params.put("isShow", "false");
					params.put("token", token);
					try {
						logger.info("ProductService.synchronous==>同步状态：" + synchronous);
						if (synchronous) {
							TmTpProductDetail detailParam = new TmTpProductDetail();
							detailParam.setSku(sku);
							TmTpProductDetail po = productDetailMapper.selectOne(detailParam);
							if (po != null && (po.getWxstate() == null || po.getWxstate() == 30031002)) {
								logger.info("ProductService.synchronous==>商品已存在且为下架：" + po.getWxstate() + "不需同步");
							} else {
								// 获取商品详情信息
								getDetail(params);

							}
						} else {
							// 获取商品详情信息
							getDetail(params);
						}
					} catch (Exception e) {
						logger.info("ProductService.querySku==>" + sku + "商品详情信息保存失败");
						logger.info("ProductService.querySku==>错误信息：" + e);
						i++;
					}
				}
				TmTpProductPoolTemp productPoolTempPo = new TmTpProductPoolTemp();
				productPoolTempPo.setStatus(JDInterfaceConstant.PRODUCT_POOL_1002);
				productPoolTempPo.setUpdateDate(new Date());
				productPoolTempPo.setUpdateBy(JDInterfaceConstant.WX_USER_ID);
				productPoolTempPo.setFalseNum(i);
				Example example1 = new Example(TmTpProductPoolTemp.class);
				Criteria criteria1 = example1.createCriteria();
				criteria1.andCondition("page_num=", pool);
				productPoolTempMapper.updateByExampleSelective(productPoolTempPo, example1);
			} else {
				logger.error("ProductService.querySku==>" + pool + "商品池查询失败");
				logger.error("ProductService.querySku==>错误信息：" + data.getString("resultMessage"));
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new ServiceBizException(e.getMessage(), e);
		}
	}

	/**
	 * 获取商品池商品详情
	 * 
	 * @author lyq
	 * @date 2017年4月11日
	 * @return
	 * @throws FileStoreException
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public void getDetail(Map<String, String> params) throws FileStoreException {
		String token = params.get("token");
		String sku = params.get("sku");
		String isShow = params.get("isShow");
		String param = "token=" + token + "&sku=" + sku + "&isShow=" + isShow;
//		logger.info("ProductService.getDetail==>params:" + param);
		String result = FrameHttpUtil.sendPost(detailUrl, param);
		logger.info("ProductService.getDetail==>result:" + result);
		JSONObject data = JSONObject.fromObject(result);
		String resultCode = data.getString("resultCode");
		if (resultCode.equals(JDInterfaceConstant.RESULTCODE_0000)) {
			String skuList = data.getString("result");
			Map<String, Object> skuMap = (Map<String, Object>) JSONObject.fromObject(skuList);
			skuMap.put("pageNum", params.get("pageNum"));
			// 处理个别数据为null时报错
			TmTpProductDetail productDetailPo = dealData(skuMap);
			TmTpProductDetail detailParam = new TmTpProductDetail();
			detailParam.setSku(sku);
			TmTpProductDetail po = productDetailMapper.selectOne(detailParam);
			if (po == null) {
				productDetailPo.setCreateDate(new Date());
				productDetailPo.setCreateBy(JDInterfaceConstant.WX_USER_ID);
				productDetailMapper.insertSelective(productDetailPo);
				logger.info("ProductService.getDetail==>商品详情信息保存成功");
			} else {
				productDetailPo.setUpdateDate(new Date());
				productDetailPo.setUpdateBy(JDInterfaceConstant.WX_USER_ID);
				Example example = new Example(TmTpProductDetail.class);
				Criteria criteria = example.createCriteria();
				criteria.andCondition("sku = ", sku);
				long lo = productDetailMapper.updateByExampleSelective(productDetailPo, example);
				logger.info("ProductService.getDetail==>" + lo + "条商品详情信息更新成功");
			}
			saveSubDetail(skuMap);
		} else {
			logger.info("ProductService.getDetail==>" + sku + "号商品获取失败。。。");
			logger.info("ProductService.getDetail==>resultCode：" + resultCode + "   resultMessage："
					+ data.getString("resultMessage"));
		}

	}

	/**
	 * 保存商品详情子表
	 * 
	 * @author lyq
	 * @date 2017年4月11日
	 * @return
	 * @throws FileStoreException
	 * @throws Exception
	 */
	public void saveSubDetail(Map<String, Object> params) throws FileStoreException {
		String sku = String.valueOf(params.get("sku"));
		if (params.get("skuType") != null) {
			String skuType = String.valueOf(params.get("skuType"));
			if (skuType.equals(VEDIO)) {
				TmTpProductDetailVido param = new TmTpProductDetailVido();
				param.setSku(sku);
				long lo = productDetailVidoMapper.delete(param);
				logger.info("ProductService.saveSubDetail==>" + lo + "条商品详情vedio子表信息删除成功");
				TmTpProductDetailVido detailVedioPo = dealDataVedio(params);
				long l = productDetailVidoMapper.insertSelective(detailVedioPo);
				logger.info("ProductService.saveSubDetail==>" + l + "商品详情Vedio子表信息保存成功");
			} else if (skuType.equals(BOOK)) {
				// TmTpProductDetailBook param = new TmTpProductDetailBook();
				// param.setSku(sku);
				// long lo = productDetailBookMapper.delete(param);
				// logger.info("ProductService.saveSubDetail==>"+lo+"条商品详情vedio子表信息删除成功");
				// TmTpProductDetailBook detailBookPo = dealDataBook(params);
				// long l =
				// productDetailBookMapper.insertSelective(detailBookPo);
				// logger.info("ProductService.saveSubDetail==>"+l+"商品详情book子表信息保存成功");
			}
		} else {
			TmTpProductDetailGeneral param = new TmTpProductDetailGeneral();
			param.setSku(sku);
			long lo = productDetailGeneralMapper.delete(param);
			logger.info("ProductService.saveSubDetail==>" + lo + "条商品详情子表信息删除成功");
			TmTpProductDetailGeneral detailGeneralPo = dealDataGeneral(params);
			long l = productDetailGeneralMapper.insertSelective(detailGeneralPo);
			logger.info("ProductService.saveSubDetail==>" + l + "商品详情通用子表信息保存成功");
		}

	}

	/**
	 * 处理商品详情返回数据
	 * 
	 * @author lyq
	 * @date 2017年4月11日
	 * @return
	 * @throws FileStoreException
	 * @throws Exception
	 */
	public TmTpProductDetail dealData(Map<String, Object> params) {
		TmTpProductDetail productDetailPo = new TmTpProductDetail();
		if (params != null && params.size() > 0) {
			if (!CheckUtil.NullOrEmpty(params.get("sku"))) {
				productDetailPo.setSku(params.get("sku").toString());
			}
			if (!CheckUtil.NullOrEmpty(params.get("name"))) {
				productDetailPo.setName(params.get("name").toString());
				productDetailPo.setPcName(params.get("name").toString());
			}
			if (!CheckUtil.NullOrEmpty(params.get("brandName"))) {
				productDetailPo.setBrandname(params.get("brandName").toString());
			}
			if (!CheckUtil.NullOrEmpty(params.get("imagePath"))) {
				productDetailPo.setImagepath(params.get("imagePath").toString());
			}
			if (!CheckUtil.NullOrEmpty(params.get("productArea"))) {
				productDetailPo.setProductarea(params.get("productArea").toString());
			}
			if (!CheckUtil.NullOrEmpty(params.get("upc"))) {
				productDetailPo.setUpc(params.get("upc").toString());
			}
			if (!CheckUtil.NullOrEmpty(params.get("saleUnit"))) {
				productDetailPo.setSaleunit(params.get("saleUnit").toString());
			}
			if (!CheckUtil.NullOrEmpty(params.get("category"))) {
				String category = String.valueOf(params.get("category"));
				String arr[] = category.split(";");
				productDetailPo.setCategory1(arr[0]);
				productDetailPo.setCategory2(arr[1]);
				productDetailPo.setCategory3(arr[2]);
			}
			if (!CheckUtil.NullOrEmpty(params.get("weight"))) {
				BigDecimal bd = new BigDecimal(params.get("weight").toString());
				productDetailPo.setWeight(bd);
			}
			if (!CheckUtil.NullOrEmpty(params.get("skuType"))) {
				productDetailPo.setSkutype(params.get("skuType").toString());
			}
			productDetailPo.setPoolNo(params.get("pageNum").toString());
		} else {
			throw new ServiceBizException("处理商品详情返回result为null");
		}

		return productDetailPo;
	}

	/**
	 * 处理商品详情返回数据
	 * 
	 * @author lyq
	 * @date 2017年4月11日
	 * @return
	 * @throws FileStoreException
	 * @throws Exception
	 */
	public TmTpProductDetailGeneral dealDataGeneral(Map<String, Object> params) throws FileStoreException {
		TmTpProductDetailGeneral detailGeneralPo = new TmTpProductDetailGeneral();
		if (params != null && params.size() > 0) {
			if (!CheckUtil.NullOrEmpty(params.get("sku"))) {
				detailGeneralPo.setSku(params.get("sku").toString());
			}
			if (!CheckUtil.NullOrEmpty(params.get("param"))) {
				String param = String.valueOf(params.get("param"));
				String param_fileId = FileStore.getInstance().write("nd02", "fs01", "param.jd", param.getBytes());
				String param_fileUrl = FileStore.getInstance().getDomainURL(param_fileId);
				detailGeneralPo.setParam(param_fileUrl);
			}
			if (!CheckUtil.NullOrEmpty(params.get("shouhou"))) {
				detailGeneralPo.setShouhou(params.get("shouhou").toString());
			}
			if (!CheckUtil.NullOrEmpty(params.get("appintroduce"))) {
				String appintroduce = String.valueOf(params.get("appintroduce"));
				String appintroduce_fileId = FileStore.getInstance().write("nd02", "fs01", "appintroduce.jd",
						appintroduce.getBytes());
				String appintroduce_fileUrl = FileStore.getInstance().getDomainURL(appintroduce_fileId);
				detailGeneralPo.setAppintroduce(appintroduce_fileId);
				detailGeneralPo.setAppintroduceExtend(appintroduce_fileUrl);
			}
			if (!CheckUtil.NullOrEmpty(params.get("wareQD"))) {
				detailGeneralPo.setWareqd(params.get("wareQD").toString());
			}
			if (!CheckUtil.NullOrEmpty(params.get("introduction"))) {
				String introduction = String.valueOf(params.get("introduction"));
				String introduction_fileId = FileStore.getInstance().write("nd02", "fs01", "introduction.jd",
						introduction.getBytes());
				String introduction_fileUrl = FileStore.getInstance().getDomainURL(introduction_fileId);
				detailGeneralPo.setIntroduction(introduction_fileId);
				detailGeneralPo.setIntroductionExtend(introduction_fileUrl);
			}
			detailGeneralPo.setCreateDate(new Date());
			detailGeneralPo.setCreateBy(JDInterfaceConstant.WX_USER_ID);

		} else {
			throw new ServiceBizException("处理商品详情返回result为null");
		}

		return detailGeneralPo;
	}

	/**
	 * 处理商品详情Vedio返回数据
	 * 
	 * @author lyq
	 * @date 2017年4月11日
	 * @return
	 * @throws FileStoreException
	 * @throws Exception
	 */
	public TmTpProductDetailVido dealDataVedio(Map<String, Object> params) throws FileStoreException {
		TmTpProductDetailVido detailVedioPo = new TmTpProductDetailVido();
		if (params != null && params.size() > 0) {
			if (!CheckUtil.NullOrEmpty(params.get("sku"))) {
				detailVedioPo.setSku(params.get("sku").toString());
			}
			if (!CheckUtil.NullOrEmpty(params.get("Press"))) {
				detailVedioPo.setPress(params.get("Press").toString());
			}
			if (!CheckUtil.NullOrEmpty(params.get("Foreignname"))) {
				detailVedioPo.setForeignname(params.get("Foreignname").toString());
			}
			if (!CheckUtil.NullOrEmpty(params.get("Brand"))) {
				detailVedioPo.setBrand(params.get("Brand").toString());
			}
			if (!CheckUtil.NullOrEmpty(params.get("Format"))) {
				detailVedioPo.setFormat(params.get("Format").toString());
			}
			if (!CheckUtil.NullOrEmpty(params.get("Performer"))) {
				detailVedioPo.setPerformer(params.get("Performer").toString());
			}
			if (!CheckUtil.NullOrEmpty(params.get("Soundtrack"))) {
				detailVedioPo.setSoundtrack(params.get("Soundtrack").toString());
			}
			if (!CheckUtil.NullOrEmpty(params.get("skuType"))) {
				detailVedioPo.setSkutype(params.get("skuType").toString());
			}
			if (!CheckUtil.NullOrEmpty(params.get("Actor"))) {
				detailVedioPo.setActor(params.get("Actor").toString());
			}
			if (!CheckUtil.NullOrEmpty(params.get("Dregion"))) {
				detailVedioPo.setDregion(params.get("Dregion").toString());
			}
			if (!CheckUtil.NullOrEmpty(params.get("Voiceover"))) {
				detailVedioPo.setVoiceover(params.get("Voiceover").toString());
			}
			if (!CheckUtil.NullOrEmpty(params.get("Director"))) {
				detailVedioPo.setDirector(params.get("Director").toString());
			}
			if (!CheckUtil.NullOrEmpty(params.get("box_Contents"))) {
				detailVedioPo.setBoxContents(params.get("box_Contents").toString());
			}
			if (!CheckUtil.NullOrEmpty(params.get("Language_Subtitled"))) {
				detailVedioPo.setLanguageSubtitled(params.get("Language_Subtitled").toString());
			}
			if (!CheckUtil.NullOrEmpty(params.get("Screen_Ratio"))) {
				detailVedioPo.setScreenRatio(params.get("Screen_Ratio").toString());
			}
			if (!CheckUtil.NullOrEmpty(params.get("Media"))) {
				detailVedioPo.setMedia(params.get("Media").toString());
			}
			if (!CheckUtil.NullOrEmpty(params.get("image"))) {
				detailVedioPo.setImage(params.get("image").toString());
			}
			if (!CheckUtil.NullOrEmpty(params.get("Episode"))) {
				detailVedioPo.setEpisode(params.get("Episode").toString());
			}
			if (!CheckUtil.NullOrEmpty(params.get("Mvd_Wxjz"))) {
				detailVedioPo.setMvdWxjz(params.get("Mvd_Wxjz").toString());
			}
			if (!CheckUtil.NullOrEmpty(params.get("Publishing_Company"))) {
				detailVedioPo.setPublishingCompany(params.get("Publishing_Company").toString());
			}
			if (!CheckUtil.NullOrEmpty(params.get("ISRC"))) {
				detailVedioPo.setIsrc(params.get("ISRC").toString());
			}
			if (!CheckUtil.NullOrEmpty(params.get("Singer"))) {
				detailVedioPo.setSinger(params.get("Singer").toString());
			}
			if (!CheckUtil.NullOrEmpty(params.get("Language_Pronunciation"))) {
				detailVedioPo.setLanguagePronunciation(params.get("Language_Pronunciation").toString());
			}
			if (!CheckUtil.NullOrEmpty(params.get("Production_Company"))) {
				detailVedioPo.setProductionCompany(params.get("Production_Company").toString());
			}
			if (!CheckUtil.NullOrEmpty(params.get("Audio_Encoding_Chinese"))) {
				detailVedioPo.setAudioEncodingChinese(params.get("Audio_Encoding_Chinese").toString());
			}
			if (!CheckUtil.NullOrEmpty(params.get("Authors"))) {
				detailVedioPo.setAuthors(params.get("Authors").toString());
			}
			if (!CheckUtil.NullOrEmpty(params.get("contentDesc"))) {
				String param = String.valueOf(params.get("contentDesc"));
				String param_fileId = FileStore.getInstance().write("nd02", "fs01", "contentDesc.jd", param.getBytes());
				String param_fileUrl = FileStore.getInstance().getDomainURL(param_fileId);
				detailVedioPo.setContentdesc(param_fileUrl);
			}
			if (!CheckUtil.NullOrEmpty(params.get("Aka"))) {
				detailVedioPo.setAka(params.get("Aka").toString());
			}
			if (!CheckUtil.NullOrEmpty(params.get("Region"))) {
				detailVedioPo.setRegion(params.get("Region").toString());
			}
			if (!CheckUtil.NullOrEmpty(params.get("Copyright"))) {
				detailVedioPo.setCopyright(params.get("Copyright").toString());
			}
			if (!CheckUtil.NullOrEmpty(params.get("Package"))) {
				detailVedioPo.set_package(params.get("Package").toString());
			}
			if (!CheckUtil.NullOrEmpty(params.get("editerDesc"))) {
				String param = String.valueOf(params.get("editerDesc"));
				String param_fileId = FileStore.getInstance().write("nd02", "fs01", "editerDesc.jd", param.getBytes());
				String param_fileUrl = FileStore.getInstance().getDomainURL(param_fileId);
				detailVedioPo.setEditerdesc(param_fileUrl);
			}
			if (!CheckUtil.NullOrEmpty(params.get("Compose"))) {
				detailVedioPo.setCompose(params.get("Compose").toString());
			}
			if (!CheckUtil.NullOrEmpty(params.get("Screenwriter"))) {
				detailVedioPo.setScreenwriter(params.get("Screenwriter").toString());
			}
			if (!CheckUtil.NullOrEmpty(params.get("catalogue"))) {
				String param = String.valueOf(params.get("catalogue"));
				String param_fileId = FileStore.getInstance().write("nd02", "fs01", "catalogue.jd", param.getBytes());
				String param_fileUrl = FileStore.getInstance().getDomainURL(param_fileId);
				detailVedioPo.setCatalogue(param_fileUrl);
			}
			if (!CheckUtil.NullOrEmpty(params.get("Language_Dubbed"))) {
				detailVedioPo.setLanguageDubbed(params.get("Language_Dubbed").toString());
			}
			if (!CheckUtil.NullOrEmpty(params.get("manual"))) {
				detailVedioPo.setManual(params.get("manual").toString());
			}
			if (!CheckUtil.NullOrEmpty(params.get("Length"))) {
				detailVedioPo.setLength(params.get("Length").toString());
			}
			if (!CheckUtil.NullOrEmpty(params.get("material_Description"))) {
				detailVedioPo.setMaterialDescription(params.get("material_Description").toString());
			}
			if (!CheckUtil.NullOrEmpty(params.get("ReleaseDate"))) {
				detailVedioPo.setReleasedate(params.get("ReleaseDate").toString());
			}
			if (!CheckUtil.NullOrEmpty(params.get("comments"))) {
				String param = String.valueOf(params.get("comments"));
				String param_fileId = FileStore.getInstance().write("nd02", "fs01", "comments.jd", param.getBytes());
				String param_fileUrl = FileStore.getInstance().getDomainURL(param_fileId);
				detailVedioPo.setComments(param_fileUrl);
			}
			detailVedioPo.setCreateDate(new Date());
			detailVedioPo.setCreateBy(JDInterfaceConstant.WX_USER_ID);

		} else {
			throw new ServiceBizException("处理商品详情返回result为null");
		}

		return detailVedioPo;
	}

	/**
	 * 处理商品详情Book返回数据
	 * 
	 * @author lyq
	 * @date 2017年4月11日
	 * @return
	 * @throws FileStoreException
	 * @throws Exception
	 */
	public TmTpProductDetailBook dealDataBook(Map<String, Object> params) throws FileStoreException {
		TmTpProductDetailBook detailBookPo = new TmTpProductDetailBook();
		if (params != null && params.size() > 0) {
			if (!CheckUtil.NullOrEmpty(params.get("sku"))) {
				detailBookPo.setSku(params.get("sku").toString());
			}
			if (!CheckUtil.NullOrEmpty(params.get("Brand"))) {
				detailBookPo.setBrand(params.get("Brand").toString());
			}
			if (!CheckUtil.NullOrEmpty(params.get("Sheet"))) {
				detailBookPo.setSheet(params.get("Sheet").toString());
			}
			if (!CheckUtil.NullOrEmpty(params.get("relatedProducts"))) {
				detailBookPo.setRelatedproducts(params.get("relatedProducts").toString());
			}

			if (!CheckUtil.NullOrEmpty(params.get("ISBN"))) {
				detailBookPo.setIsbn(params.get("ISBN").toString());
			}
			if (!CheckUtil.NullOrEmpty(params.get("PrintNo"))) {
				detailBookPo.setPrintno(params.get("PrintNo").toString());
			}
			if (!CheckUtil.NullOrEmpty(params.get("Editer"))) {
				detailBookPo.setEditer(params.get("Editer").toString());
			}
			if (!CheckUtil.NullOrEmpty(params.get("Author"))) {
				detailBookPo.setAuthor(params.get("Author").toString());
			}
			if (!CheckUtil.NullOrEmpty(params.get("PackNum"))) {
				detailBookPo.setPacknum(params.get("PackNum").toString());
			}
			if (!CheckUtil.NullOrEmpty(params.get("Publishers"))) {
				detailBookPo.setPublishers(params.get("Publishers").toString());
			}
			if (!CheckUtil.NullOrEmpty(params.get("contentDesc"))) {
				String param = String.valueOf(params.get("contentDesc"));
				String param_fileId = FileStore.getInstance().write("nd02", "fs01", "contentDesc.jd", param.getBytes());
				String param_fileUrl = FileStore.getInstance().getDomainURL(param_fileId);
				detailBookPo.setContentdesc(param_fileUrl);
			}
			if (!CheckUtil.NullOrEmpty(params.get("PrintTime"))) {
				detailBookPo.setPrinttime((Date) params.get("PrintTime"));
			}
			if (!CheckUtil.NullOrEmpty(params.get("skuType"))) {
				detailBookPo.setSkutype(params.get("skuType").toString());
			}
			if (!CheckUtil.NullOrEmpty(params.get("Papers"))) {
				detailBookPo.setPapers(params.get("Papers").toString());
			}
			if (!CheckUtil.NullOrEmpty(params.get("Package"))) {
				detailBookPo.set_package(params.get("Package").toString());
			}
			if (!CheckUtil.NullOrEmpty(params.get("Proofreader"))) {
				detailBookPo.setProofreader(params.get("Proofreader").toString());
			}
			if (!CheckUtil.NullOrEmpty(params.get("editerDesc"))) {
				String param = String.valueOf(params.get("editerDesc"));
				String param_fileId = FileStore.getInstance().write("nd02", "fs01", "editerDesc.jd", param.getBytes());
				String param_fileUrl = FileStore.getInstance().getDomainURL(param_fileId);
				detailBookPo.setEditerdesc(param_fileUrl);
			}
			if (!CheckUtil.NullOrEmpty(params.get("bookAbstract"))) {
				detailBookPo.setBookabstract(params.get("bookAbstract").toString());
			}
			if (!CheckUtil.NullOrEmpty(params.get("catalogue"))) {
				detailBookPo.setCatalogue(params.get("catalogue").toString());
			}
			if (!CheckUtil.NullOrEmpty(params.get("PublishTime"))) {
				detailBookPo.setPublishtime((Date) params.get("PublishTime"));
			}
			if (!CheckUtil.NullOrEmpty(params.get("Pages"))) {
				detailBookPo.setPages(params.get("Pages").toString());
			}
			if (!CheckUtil.NullOrEmpty(params.get("authorDesc"))) {
				String param = String.valueOf(params.get("authorDesc"));
				String param_fileId = FileStore.getInstance().write("nd02", "fs01", "authorDesc.jd", param.getBytes());
				String param_fileUrl = FileStore.getInstance().getDomainURL(param_fileId);
				detailBookPo.setAuthordesc(param_fileUrl);
			}
			if (!CheckUtil.NullOrEmpty(params.get("image"))) {
				detailBookPo.setImage(params.get("image").toString());
			}
			if (!CheckUtil.NullOrEmpty(params.get("Transfer"))) {
				detailBookPo.setTransfer(params.get("Transfer").toString());
			}
			if (!CheckUtil.NullOrEmpty(params.get("Drawer"))) {
				detailBookPo.setDrawer(params.get("Drawer").toString());
			}
			if (!CheckUtil.NullOrEmpty(params.get("Language"))) {
				detailBookPo.setLanguage(params.get("Language").toString());
			}
			if (!CheckUtil.NullOrEmpty(params.get("BatchNo"))) {
				detailBookPo.setBatchno(params.get("BatchNo").toString());
			}
			if (!CheckUtil.NullOrEmpty(params.get("introduction"))) {
				detailBookPo.setIntroduction(params.get("introduction").toString());
			}
			if (!CheckUtil.NullOrEmpty(params.get("comments"))) {
				String param = String.valueOf(params.get("comments"));
				String param_fileId = FileStore.getInstance().write("nd02", "fs01", "comments.jd", param.getBytes());
				String param_fileUrl = FileStore.getInstance().getDomainURL(param_fileId);
				detailBookPo.setComments(param_fileUrl);
			}
			detailBookPo.setCreateDate(new Date());
			detailBookPo.setCreateBy(JDInterfaceConstant.WX_USER_ID);

		} else {
			throw new ServiceBizException("处理商品详情返回result为null");
		}

		return detailBookPo;
	}

	/**
	 * 获取商品上下架状态
	 * 
	 * @author lyq
	 * @date 2017年4月17日
	 * @return
	 * @throws Exception
	 */
	public Map<String, Object> skuState() {
		try {
			Example example = new Example(TmTpProductPoolTemp.class);
//			Criteria criteria = example.createCriteria();
//			criteria.andCondition("go_down_state=", JDInterfaceConstant.PRODUCT_POOL_1001);
			example.setOrderByClause("PAGE_NUM ASC");
			List<TmTpProductPoolTemp> poolList = productPoolTempMapper.selectByExample(example);
			BaseThread plate = new BaseThread();
			// 生产者线程
			new Thread(new AddBaseThread(plate, poolList)).start();

			// 消费者线程
			for (int i = 0; i < synchronousNum; i++) {
				new Thread(new GetSkuStateThread(plate, this)).start();
			}
			Map<String, Object> map = new HashMap<>();
			map.put("resultCode", JDInterfaceConstant.RESULTCODE_0000);
			return map;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new ServiceBizException(e.getMessage(), e);
		}
	}

	/**
	 * 获取商品上下架状态
	 * 
	 * @author lyq
	 * @date 2017年4月17日
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public void querySkuState(Integer pool) {
		try {
			String token = jdInterfaceService.getToken();
			Map<String, Object> pa = new HashMap<String, Object>();

			Integer wxstate = null;
			logger.info("ProductService.synchronous==>同步状态：" + synchronous);
			if (synchronous) {
				wxstate = JDInterfaceConstant.WX_STATUS_UP;
			}
			pa.put("pageNum", pool);
			pa.put("wxstate", wxstate);

			List<String> list = productDetailMapper.selectAllSku(pa);
			if (list != null && list.size() > 0) {
				String arr[] = productGroupBySku(list);
				for (int i = 0; i < arr.length; i++) {
					String param = "token=" + token + "&sku=" + arr[i];
//					logger.info("ProductService.skuState==>params:" + param);
					String result = FrameHttpUtil.sendPost(skuStateUrl, param);
					logger.info("ProductService.skuState==>result:" + result);
					JSONObject data = JSONObject.fromObject(result);
					String resultCode = data.getString("resultCode");
					if (resultCode.equals(JDInterfaceConstant.RESULTCODE_0000)) {
						JSONArray pList = data.getJSONArray("result");
						List<ProductStatePO> ppList = JSONArray.toList(pList, new ProductStatePO(), new JsonConfig());
						for (ProductStatePO pp : ppList) {
							String state = "";
							if (pp.getState().equals("1")) {
								state = JDInterfaceConstant.JD_STATUS_UP.toString();
							} else if (pp.getState().equals("0")) {
								state = JDInterfaceConstant.JD_STATUS_DOWN.toString();
							}
							long ty = productDetailMapper.updateProductState(pp.getSku(), state);
							if (ty == 1) {
								logger.info("ProductService.skuState==>" + pp.getSku() + "商品上下架状态更新成功！");
							} else {
								logger.info("ProductService.skuState==>" + pp.getSku() + "商品上下架状态更新失败！");
							}
						}
					} else {
//						logger.error("ProductService.getJdPrice==>" + pool + "号商品池" + arr[i] + "商品京东价格获取失败！");
						logger.error("ProductService.getJdPrice==>error:" + data.getString("resultMessage"));
					}
				}
				TmTpProductPoolTemp productPoolTempPo = new TmTpProductPoolTemp();
				productPoolTempPo.setGoDownState(JDInterfaceConstant.PRODUCT_POOL_1002);
				productPoolTempPo.setUpdateDate(new Date());
				productPoolTempPo.setUpdateBy(JDInterfaceConstant.WX_USER_ID);
				Example example1 = new Example(TmTpProductPoolTemp.class);
				Criteria criteria1 = example1.createCriteria();
				criteria1.andCondition("page_num=", pool);
				productPoolTempMapper.updateByExampleSelective(productPoolTempPo, example1);
			} else {
				TmTpProductPoolTemp productPoolTempPo = new TmTpProductPoolTemp();
				productPoolTempPo.setGoDownState(JDInterfaceConstant.PRODUCT_POOL_1002);
				productPoolTempPo.setUpdateDate(new Date());
				productPoolTempPo.setUpdateBy(JDInterfaceConstant.WX_USER_ID);
				Example example1 = new Example(TmTpProductPoolTemp.class);
				Criteria criteria1 = example1.createCriteria();
				criteria1.andCondition("page_num=", pool);
				productPoolTempMapper.updateByExampleSelective(productPoolTempPo, example1);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new ServiceBizException(e.getMessage(), e);
		}
	}

	/**
	 * 获取商品京东价格
	 * 
	 * @author lyq
	 * @date 2017年4月17日
	 * @return
	 * @throws Exception
	 */
	public Map<String, Object> getJdPrice() {
		try {

			Example example = new Example(TmTpProductPoolTemp.class);
			Criteria criteria = example.createCriteria();
			criteria.andCondition("jdprice_state=", JDInterfaceConstant.PRODUCT_POOL_1001);
			example.setOrderByClause("PAGE_NUM ASC");
			List<TmTpProductPoolTemp> poolList = productPoolTempMapper.selectByExample(example);
			BaseThread plate = new BaseThread();
			// 生产者线程
			new Thread(new AddBaseThread(plate, poolList)).start();

			// 消费者线程
			for (int i = 0; i < synchronousNum; i++) {
				new Thread(new GetJdPriceThread(plate, this)).start();
			}
			Map<String, Object> map = new HashMap<>();
			map.put("resultCode", JDInterfaceConstant.RESULTCODE_0000);
			return map;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new ServiceBizException(e.getMessage(), e);
		}
	}

	/**
	 * 获取商品京东价格
	 * 
	 * @author lyq
	 * @date 2017年4月17日
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public void queryJdPrice(Integer pool) {
		try {
			String token = jdInterfaceService.getToken();
			Map<String, Object> pa = new HashMap<String, Object>();

			Integer wxstate = null;
			if (synchronous) {
				wxstate = JDInterfaceConstant.WX_STATUS_UP;
			}
			pa.put("pageNum", pool);
			pa.put("wxstate", wxstate);

			List<String> list = productDetailMapper.selectAllSku(pa);
			if (list != null && list.size() > 0) {
				String arr[] = productGroupBySku(list);
				for (int i = 0; i < arr.length; i++) {
					String param = "token=" + token + "&sku=" + arr[i];
					logger.info("ProductService.getJdPrice==>params:" + param);
					String result = FrameHttpUtil.sendPost(jdPriceUrl, param);
					logger.info("ProductService.getJdPrice==>result:" + result);
					JSONObject data = JSONObject.fromObject(result);
					String resultCode = data.getString("resultCode");
					if (resultCode.equals(JDInterfaceConstant.RESULTCODE_0000)) {
						JSONArray pList = data.getJSONArray("result");
						List<ProductPricePO> ppList = JSONArray.toList(pList, new ProductPricePO(), new JsonConfig());
						for (ProductPricePO pp : ppList) {
							long ty = productDetailMapper.updateProductJdPrice(pp.getSkuId(), pp.getJdPrice());
							if (ty == 1) {
								logger.info("ProductService.getJdPrice==>" + pp.getSkuId() + "商品京东价格更新成功！");
							} else {
								logger.info("ProductService.getJdPrice==>" + pp.getSkuId() + "商品京东价格更新失败！");
							}
						}
					} else {
//						logger.error("ProductService.getJdPrice==>" + pool + "号商品池" + arr[i] + "商品京东价格获取失败！");
						logger.error("ProductService.getJdPrice==>error:" + data.getString("resultMessage"));
					}
				}
				TmTpProductPoolTemp productPoolTempPo = new TmTpProductPoolTemp();
				productPoolTempPo.setJdpriceState(JDInterfaceConstant.PRODUCT_POOL_1002);
				productPoolTempPo.setUpdateDate(new Date());
				productPoolTempPo.setUpdateBy(JDInterfaceConstant.WX_USER_ID);
				Example example1 = new Example(TmTpProductPoolTemp.class);
				Criteria criteria1 = example1.createCriteria();
				criteria1.andCondition("page_num=", pool);
				productPoolTempMapper.updateByExampleSelective(productPoolTempPo, example1);
			} else {
				TmTpProductPoolTemp productPoolTempPo = new TmTpProductPoolTemp();
				productPoolTempPo.setJdpriceState(JDInterfaceConstant.PRODUCT_POOL_1002);
				productPoolTempPo.setUpdateDate(new Date());
				productPoolTempPo.setUpdateBy(JDInterfaceConstant.WX_USER_ID);
				Example example1 = new Example(TmTpProductPoolTemp.class);
				Criteria criteria1 = example1.createCriteria();
				criteria1.andCondition("page_num=", pool);
				productPoolTempMapper.updateByExampleSelective(productPoolTempPo, example1);
			}

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new ServiceBizException(e.getMessage(), e);
		}
	}

	/**
	 * 获取商品协议价格
	 * 
	 * @author lyq
	 * @date 2017年4月17日
	 * @return
	 * @throws Exception
	 */
	public Map<String, Object> getPrice() {
		try {
			Example example = new Example(TmTpProductPoolTemp.class);
			Criteria criteria = example.createCriteria();
			criteria.andCondition("price_state=", JDInterfaceConstant.PRODUCT_POOL_1001);
			example.setOrderByClause("PAGE_NUM ASC");
			List<TmTpProductPoolTemp> poolList = productPoolTempMapper.selectByExample(example);
			BaseThread plate = new BaseThread();
			// 生产者线程
			new Thread(new AddBaseThread(plate, poolList)).start();

			// 消费者线程
			for (int i = 0; i < synchronousNum; i++) {
				new Thread(new GetPriceThread(plate, this)).start();
			}
			Map<String, Object> map = new HashMap<>();
			map.put("resultCode", JDInterfaceConstant.RESULTCODE_0000);
			return map;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new ServiceBizException(e.getMessage(), e);
		}
	}

	/**
	 * 获取商品协议价格
	 * 
	 * @author lyq
	 * @date 2017年4月17日
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public void queryPrice(Integer pool) {
		try {
			String token = jdInterfaceService.getToken();
			Map<String, Object> pa = new HashMap<String, Object>();

			Integer wxstate = null;
			if (synchronous) {
				wxstate = JDInterfaceConstant.WX_STATUS_UP;
			}
			pa.put("pageNum", pool);
			pa.put("wxstate", wxstate);

			List<String> list = productDetailMapper.selectAllSku(pa);
			if (list != null && list.size() > 0) {
				String arr[] = productGroupBySku(list);
				for (int i = 0; i < arr.length; i++) {
					String param = "token=" + token + "&sku=" + arr[i];
//					logger.info("ProductService.getPrice==>params:" + param);
					String result = FrameHttpUtil.sendPost(priceUrl, param);
					logger.info("ProductService.getPrice==>result:" + result);
					JSONObject data = JSONObject.fromObject(result);
					String resultCode = data.getString("resultCode");
					if (resultCode.equals(JDInterfaceConstant.RESULTCODE_0000)) {
						JSONArray pList = data.getJSONArray("result");
						List<ProductPricePO> ppList = JSONArray.toList(pList, new ProductPricePO(), new JsonConfig());
						for (ProductPricePO pp : ppList) {
							long ty = productDetailMapper.updateProductPrice(pp.getSkuId(), pp.getPrice());
							if (ty == 1) {
								logger.info("ProductService.getPrice==>" + pp.getSkuId() + "商品协议价格更新成功！");
							} else {
								logger.info("ProductService.getPrice==>" + pp.getSkuId() + "商品协议价格更新失败！");
							}
						}
					} else {
//						logger.error("ProductService.getPrice==>" + pool + "号商品池" + arr[i] + "商品协议价格获取失败！");
						logger.error("ProductService.getPrice==>error:" + data.getString("resultMessage"));
					}
				}
				TmTpProductPoolTemp productPoolTempPo = new TmTpProductPoolTemp();
				productPoolTempPo.setPriceState(JDInterfaceConstant.PRODUCT_POOL_1002);
				productPoolTempPo.setUpdateDate(new Date());
				productPoolTempPo.setUpdateBy(JDInterfaceConstant.WX_USER_ID);
				Example example1 = new Example(TmTpProductPoolTemp.class);
				Criteria criteria1 = example1.createCriteria();
				criteria1.andCondition("page_num=", pool);
				productPoolTempMapper.updateByExampleSelective(productPoolTempPo, example1);
			} else {
				TmTpProductPoolTemp productPoolTempPo = new TmTpProductPoolTemp();
				productPoolTempPo.setPriceState(JDInterfaceConstant.PRODUCT_POOL_1002);
				productPoolTempPo.setUpdateDate(new Date());
				productPoolTempPo.setUpdateBy(JDInterfaceConstant.WX_USER_ID);
				Example example1 = new Example(TmTpProductPoolTemp.class);
				Criteria criteria1 = example1.createCriteria();
				criteria1.andCondition("page_num=", pool);
				productPoolTempMapper.updateByExampleSelective(productPoolTempPo, example1);
			}

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new ServiceBizException(e.getMessage(), e);
		}
	}

	/**
	 * 获取商品分类信息
	 * 
	 * @author lyq
	 * @date 2017年4月17日
	 * @return
	 * @throws Exception
	 */
	public Map<String, Object> getCategory(Map<String, String> params) {
		try {
			Map<String, Object> map = new HashMap<>();
			String token = params.get("token");
			List<TmTpProductDetail> list = productDetailMapper.queryProduct();
			for (TmTpProductDetail po : list) {
				String param1 = "token=" + token + "&cid=" + po.getCategory1();
				map = sendCategory(param1);
				String param2 = "token=" + token + "&cid=" + po.getCategory2();
				map = sendCategory(param2);
				String param3 = "token=" + token + "&cid=" + po.getCategory3();
				map = sendCategory(param3);
			}
			return map;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new ServiceBizException(e.getMessage(), e);
		}
	}

	/**
	 * 获取商品分类信息
	 * 
	 * @author lyq
	 * @date 2017年4月17日
	 * @return
	 * @throws Exception
	 */
	public Map<String, Object> sendCategory(String param) {
		try {
			Map<String, Object> map = new HashMap<>();
			//扫描  1159
			//logger.info("ProductService.sendCategory==>params:" + param);
			String result = FrameHttpUtil.sendPost(categorySku, param);
			//logger.info("ProductService.sendCategory==>result:" + result);
			JSONObject data = JSONObject.fromObject(result);
			String resultCode = data.getString("resultCode");
			map.put("success", data.getString("success"));
			map.put("resultMessage", data.getString("resultMessage"));
			map.put("resultCode", resultCode);
			if (resultCode.equals(JDInterfaceConstant.RESULTCODE_0000)) {
				JSONObject obj = data.getJSONObject("result");
				TmTpProductCategory categoy = (TmTpProductCategory) JSONObject.toBean(obj, TmTpProductCategory.class);
				if (categoy.getCatClass() == 0) {
					categoy.setCatClass(JDInterfaceConstant.CATEGOY_CLASS_1001);
				} else if (categoy.getCatClass() == 1) {
					categoy.setCatClass(JDInterfaceConstant.CATEGOY_CLASS_1002);
				} else if (categoy.getCatClass() == 2) {
					categoy.setCatClass(JDInterfaceConstant.CATEGOY_CLASS_1003);
				}
				if (categoy.getState() == 0) {
					categoy.setState(JDInterfaceConstant.CATEGOY_TYPE_FALSE);
				} else if (categoy.getState() == 1) {
					categoy.setState(JDInterfaceConstant.CATEGOY_TYPE_TRUE);
				}
				TmTpProductCategory par = new TmTpProductCategory();
				par.setCatId(categoy.getCatId());
				List<TmTpProductCategory> catList = productCategoryMapper.select(par);
				if (catList != null && catList.size() > 0) {
					categoy.setUpdateDate(new Date());
					categoy.setUpdateBy(JDInterfaceConstant.WX_USER_ID);
					Example example = new Example(TmTpProductCategory.class);
					Criteria criteria = example.createCriteria();
					criteria.andCondition("cat_id = ", categoy.getCatId());
					int j = productCategoryMapper.updateByExampleSelective(categoy, example);
					if (j == 1) {
						logger.info("ProductService.sendCategory==>" + categoy.getCatId() + "商品类更新成功！");
					} else {
						logger.info("ProductService.sendCategory==>" + categoy.getCatId() + "商品类更新失败！");
					}
				} else {
					categoy.setCreateDate(new Date());
					categoy.setCreateBy(JDInterfaceConstant.WX_USER_ID);
					int i = productCategoryMapper.insertSelective(categoy);
					if (i == 1) {
						logger.info("ProductService.sendCategory==>" + categoy.getCatId() + "商品类插入成功！");
					} else {
						logger.info("ProductService.sendCategory==>" + categoy.getCatId() + "商品类插入失败！");
					}
				}
			}

			return map;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new ServiceBizException(e.getMessage(), e);
		}
	}

	/**
	 * 对所有商品进行分组
	 * 
	 * @param list
	 * @return
	 */
	public String[] productGroupBy(List<TmTpProductDetail> list) {
		// 商品sku,100个一组，总共要分的组数
		int number = (list.size() - list.size() % 100) / 100 + 1;
		// 记录不足100的商品组
		int num = list.size() % 100;
		String arr[] = new String[number];
		String sku = "";
		// 每组的商品数
		int i = 1;
		int j = 0;
		// 记录已分的组
		int k = 1;
		for (TmTpProductDetail po : list) {
			sku += po.getSku() + ",";
			if (number > 1 && k < number) {
				if (i % 100 == 0) {
					arr[j] = sku.substring(0, sku.length() - 1);
					sku = "";
					j++;
					k++;
					i = 1;
				}
			} else {
				if (i == num) {
					arr[j] = sku.substring(0, sku.length() - 1);
					sku = "";
					j++;
				}

			}
			i++;
		}
		return arr;
	}

	/**
	 * 对所有商品进行分组
	 * 
	 * @param list
	 * @return
	 */
	public String[] productGroupBySku(List<String> list) {
		// 商品sku,100个一组，总共要分的组数
		int number = (list.size() - list.size() % 100) / 100 + 1;
		// 记录不足100的商品组
		int num = list.size() % 100;
		String arr[] = new String[number];
		String sku = "";
		// 每组的商品数
		int i = 1;
		int j = 0;
		// 记录已分的组
		int k = 1;
		for (String po : list) {
			sku += po + ",";
			if (number > 1 && k < number) {
				if (i % 100 == 0) {
					arr[j] = sku.substring(0, sku.length() - 1);
					sku = "";
					j++;
					k++;
					i = 1;
				}
			} else {
				if (i == num) {
					arr[j] = sku.substring(0, sku.length() - 1);
					sku = "";
					j++;
				}

			}
			i++;
		}
		return arr;
	}

	/**
	 * 8.1企销接口返回
	 * 
	 * @author liyujiao
	 * @date 2017年4月17日
	 * @return Map
	 */
	@SuppressWarnings("unchecked")
	public void getEnterpriseMarketing(String type) {
		try {
			String token = jdInterfaceService.getToken();
			int totalPage =1;//总页数 （默认1页，具体根据京东返回页数为准）
			int nowPage =0;//当前页数
			String url = "new".equals(type) ? getNewOrder
					: "dlok".equals(type) ? getDlokOrder : "refuse".equals(type) ? getRefuseOrder : "";
	
			if ("".equals(url)) {
				logger.info("ProductService.getEnterpriseMarketing==>url is null!");
				return;
			}
			logger.info("ProductService.getEnterpriseMarketing==>token值：" + token);
			String date = DateUtil.formateDate(DateUtil.subtractDay(JdOrderDay), "yyyy-MM-dd");
			logger.info("ProductService.getEnterpriseMarketing==>date值：" + date);
			
			do{
				nowPage++;
				logger.info("ProductService.getEnterpriseMarketing==>总页数"+totalPage+"   开始查询第" + nowPage+"页");
				String param = "token=" + token + "&date=" + date+ "&page="+nowPage;
				logger.info("ProductService.getEnterpriseMarketing==>params:" + param);
		
				String result = FrameHttpUtil.sendPost(url, param);
//				result = "{\"result\":{\"orders\":[{\"jdOrderId\":111111, \"state\":0, \"hangUpState\":0 , \"invoiceState\":0, \"orderPrice\":111.11 },{\"jdOrderId\":222222, \"state\":0, \"hangUpState\":0 , \"invoiceState\":0, \"orderPrice\":222.22 }],\"total\":100, \"totalPage\":5,\"curPage\":1}}";
				logger.info("ProductService.getEnterpriseMarketing==>result:" + result);
				if(!CheckUtil.NullOrEmpty(result)){
					JSONObject data1 = JSONObject.fromObject(result);
					if(!JDInterfaceConstant.RESULTCODE_0000.equals(data1.getString("resultCode"))){
						logger.info("ProductService.getEnterpriseMarketing==>京东接口调用失败：" + data1.getString("resultMessage"));
						logger.error("ProductService.getEnterpriseMarketing==>京东接口调用失败：" + data1.getString("resultMessage"));
						return;
					}
					String result1 = data1.getString("result");
					if("".equals(data1.getString("resultCode"))){
						logger.info("ProductService.getEnterpriseMarketing==>result is null ...");
						logger.error("ProductService.getEnterpriseMarketing==>result is null ...");
						return;
					}
					JSONObject data = JSONObject.fromObject(result1);
					JSONArray arr = data.getJSONArray("orders");
					totalPage = data.getInt("totalPage");
					for (Object object : arr) {
						Map<String, Object> map = (Map<String, Object>) object;
						String state = map.get("state").toString();
						Long jdOrderId = Long.valueOf(map.get("jdOrderId").toString());
						String jdTime = DateUtil.formateString(map.get("time").toString(),"yyyy-MM-dd");
						BigDecimal jdPrice = new BigDecimal(map.get("orderPrice").toString());
						TmTpEnterpriseMarketing enterprise = new TmTpEnterpriseMarketing();
						enterprise.setJdOrderId(jdOrderId);
						enterprise.setState(Short.valueOf(state));
						enterprise.setHangUpState(Short.valueOf(map.get("hangUpState").toString()));
						enterprise.setInvoiceState(Short.valueOf(map.get("invoiceState").toString()));
						enterprise.setOrderPrice(jdPrice);
						enterprise.setTime(jdTime);
						TmTpEnterpriseMarketing coun = new TmTpEnterpriseMarketing();
						coun.setJdOrderId(Long.valueOf(map.get("jdOrderId").toString()));
						int i = tmTpEnterpriseMarketingMapper.selectCount(coun);
						if(i>0){
							Example e = new Example(TmTpEnterpriseMarketing.class);
							Criteria criteria = e.createCriteria();
							criteria.andEqualTo("jdOrderId", Long.valueOf(map.get("jdOrderId").toString()));
							tmTpEnterpriseMarketingMapper.updateByExampleSelective(enterprise, e);
						}else{
							tmTpEnterpriseMarketingMapper.insertSelective(enterprise);
						}
						//查询商城订单
						TmTpOrderInfo order = new TmTpOrderInfo();
						order.setJdOrderId(jdOrderId.toString());
						TmTpOrderInfo reOrder = TmTpOrderInfoMapper.selectOne(order);
						
						BigDecimal orderPrice = reOrder==null?new BigDecimal(0):new BigDecimal(reOrder.getOrderPrice());
						String orderTime = reOrder==null?"":DateUtil.formateDate(reOrder.getCreateDate(),"yyyy-MM-dd");
						//商城订单存在，状态为已完成，与京东价格一致，与京东时间在同一天，京东状态为新建时，跳过不记录，否则记录
						if(reOrder!=null && "30051007".equals(reOrder.getOrderStatus()) &&jdPrice==orderPrice
								&& orderTime.equals(jdTime) && "0".equals(state) ){
							continue;
						}
						
						TtJdOrderVarianc varianc = new TtJdOrderVarianc();
						varianc.setJdOrderId(jdOrderId);
						varianc.setJdPrice(jdPrice);
						varianc.setState(Short.valueOf(state));
						varianc.setJdTime(jdTime);
						varianc.setOrderPrice(orderPrice);
						varianc.setOrderTime(orderTime);
						varianc.setVariancState((short) 1);
						if(reOrder!=null){
							varianc.setVariancState((short) 0);
							varianc.setWxState(Integer.valueOf(reOrder.getOrderStatus()));
						}
						jdOrderVariancMapper.insertSelective(varianc);
						logger.info("ProductService.getEnterpriseMarketing==>save order varianc ...");
					}
				}
				
			} while(totalPage!=nowPage);
			
			List<TmTpOrderInfo> list = TmTpOrderInfoMapper.selectOrder(date);
			if(!CheckUtil.NullOrEmpty(list) && !list.isEmpty()){
				for (TmTpOrderInfo or : list) {
					TtJdOrderVarianc varianc = new TtJdOrderVarianc();
					varianc.setJdOrderId(Long.valueOf(or.getJdOrderId()));
					varianc.setOrderPrice(new BigDecimal(or.getOrderPrice()));
					varianc.setWxState(Integer.valueOf(or.getOrderStatus()));
					varianc.setOrderTime(date);
					varianc.setVariancState((short) 2);
					jdOrderVariancMapper.insertSelective(varianc);
					logger.info("ProductService.getEnterpriseMarketing==>save weixin order ...");
				}
			}
		} catch (Exception e) {
			logger.warn("ProductService.getEnterpriseMarketing==>异常：" + e.getMessage());
			logger.error("ProductService.getEnterpriseMarketing==>异常：" + e.getMessage(),e);
		}
	}
	public PageInfo<TtJdOrderVarianc> variancOrder(Map<String, Object> paramMap) {
        try {
            Page<TtJdOrderVarianc> ss = PageHelper.startPage(Integer.parseInt(paramMap.get("pageNum").toString()),
                                                          Integer.parseInt(paramMap.get("pageSize").toString()));
            logger.info("ss为————" + ss);

            List<TtJdOrderVarianc> orderList = jdOrderVariancMapper.queryVariancList(paramMap);
            logger.info("pd为————" + orderList.toString());
            PageInfo<TtJdOrderVarianc> page = new PageInfo<TtJdOrderVarianc>(orderList);
            logger.info("page为————" + page);
            return page;

        } catch (Exception e) {
            logger.info("Exception:", e);
            throw new ServiceBizException(e.getMessage(), e);
        }
    }
	/**
     * 导出订单信息
     * 
     */
    public List<TtJdOrderVarianc> variancOrderExport(Map<String, Object> paramMap){
        try {
        	List<TtJdOrderVarianc> orderList = jdOrderVariancMapper.queryVariancList(paramMap);
            logger.info("pd为————" + orderList.toString());
            return orderList;
        } catch (Exception e) {
            logger.info("Exception:", e);
            throw new ServiceBizException(e.getMessage(), e);
        }
    }
	public Map<String, Object> getSimilarSku() {
		Example example = new Example(TmTpProductPoolTemp.class);
		Criteria criteria = example.createCriteria();
		criteria.andCondition("similar_state=", JDInterfaceConstant.PRODUCT_POOL_1001);
		example.setOrderByClause("PAGE_NUM ASC");
		List<TmTpProductPoolTemp> poolList = productPoolTempMapper.selectByExample(example);
		BaseThread plate = new BaseThread();
		// 生产者线程
		new Thread(new AddBaseThread(plate, poolList)).start();

		// 消费者线程
		for (int i = 0; i < synchronousNum; i++) {
			new Thread(new GetSaleStateThread(plate, this)).start();
		}
		Map<String, Object> map = new HashMap<>();
		map.put("resultCode", JDInterfaceConstant.RESULTCODE_0000);
		return map;
	}

	@SuppressWarnings("unchecked")
	public void querySimilarSku(Integer pool) {
		try {
			Map<String, Object> pa = new HashMap<String, Object>();
			String token = jdInterfaceService.getToken();
			Integer wxstate = null;
			if (synchronous) {
				wxstate = JDInterfaceConstant.WX_STATUS_UP;
			}
			pa.put("pageNum", pool);
			pa.put("wxstate", wxstate);

			List<String> list = productDetailMapper.selectAllSku(pa);
			if (list != null && list.size() > 0) {
				for (String sku : list) {

					String param = "token=" + token + "&skuId=" + sku;
//					logger.info("ProductService.getSimilarSku==>params:" + param);

					productGroupMapper.deleteProductGroup(sku);

					String result = FrameHttpUtil.sendPost(getSimilarSku, param);
					logger.info("ProductService.getSimilarSku==>result:" + result);
					JSONObject data = JSONObject.fromObject(result);
					boolean success = data.getBoolean("success");
					if (success) {
						JSONArray pList = data.getJSONArray("result");
						for (int i = 0; i < pList.size(); i++) {
							List<Map<String, Object>> saveList = new ArrayList<Map<String, Object>>();
							Map<String, Object> map = (Map<String, Object>) pList.get(i);
							String dim = String.valueOf(map.get("dim"));
							String saleName = String.valueOf(map.get("saleName"));
							JSONArray saleAttr = (JSONArray) map.get("saleAttrList");
							for (int j = 0; j < saleAttr.size(); j++) {

								Map<String, Object> saleMap = (Map<String, Object>) saleAttr.get(j);
								String skuId = saleMap.get("skuIds").toString().replace("[", "").replace("]", "");
								String imagePath = String.valueOf(saleMap.get("imagePath"));
								String saleValue = String.valueOf(saleMap.get("saleValue"));
								Map<String, Object> m = new HashMap<String, Object>();
								m.put("dim", dim);
								m.put("saleName", saleName);
								m.put("sku", skuId);
								m.put("inputSku", sku);
								m.put("imagePath", (null == imagePath || "".equals(imagePath)
										|| "null".equalsIgnoreCase(imagePath)) ? "" : imagePath);
								m.put("saleValue", (null == saleValue || "".equals(saleValue)
										|| "null".equalsIgnoreCase(saleValue)) ? "" : saleValue);
								saveList.add(m);
							}
							if (saveList.size() != 0) {
								productGroupMapper.saveProductGroup(saveList);
							}
						}
					}

				}
				TmTpProductPoolTemp productPoolTempPo = new TmTpProductPoolTemp();
				productPoolTempPo.setSimilarState(JDInterfaceConstant.PRODUCT_POOL_1002);
				productPoolTempPo.setUpdateDate(new Date());
				productPoolTempPo.setUpdateBy(JDInterfaceConstant.WX_USER_ID);
				Example example1 = new Example(TmTpProductPoolTemp.class);
				Criteria criteria1 = example1.createCriteria();
				criteria1.andCondition("page_num=", pool);
				productPoolTempMapper.updateByExampleSelective(productPoolTempPo, example1);
			} else {
				TmTpProductPoolTemp productPoolTempPo = new TmTpProductPoolTemp();
				productPoolTempPo.setSimilarState(JDInterfaceConstant.PRODUCT_POOL_1002);
				productPoolTempPo.setUpdateDate(new Date());
				productPoolTempPo.setUpdateBy(JDInterfaceConstant.WX_USER_ID);
				Example example1 = new Example(TmTpProductPoolTemp.class);
				Criteria criteria1 = example1.createCriteria();
				criteria1.andCondition("page_num=", pool);
				productPoolTempMapper.updateByExampleSelective(productPoolTempPo, example1);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new ServiceBizException(e.getMessage(), e);
		}
	}

	/**
	 * 插入规格
	 * 
	 * @param token
	 */
	public Integer insertCategorys(String token, Integer pageNo, Integer catClass) {
		Integer totalRows = 0;
		try {
			String url = categoryUrl;
			// Integer pageNo=1;
			Integer pageSize = 5000;
			// Integer catClass=0;
			String params = "token=" + token + "&pageNo=" + pageNo + "&pageSize=" + pageSize + "&catClass=" + catClass;
//			logger.info("==>params:" + params);
			String result = FrameHttpUtil.sendPost(url, params);
			logger.info("==>result:" + result);
			JSONObject data = JSONObject.fromObject(result);
			logger.info("=========>data:" + data);
			JSONObject categorysResult = data.getJSONObject("result");
			logger.info("=========>categorysResult:" + categorysResult);
			JSONArray categorys = categorysResult.getJSONArray("categorys");
			logger.info("=========>categorys:" + categorys);
			totalRows = Integer.valueOf(categorysResult.get("totalRows").toString());
			logger.info("=========>totalRows:" + totalRows);
			TmTpProductCategory param = new TmTpProductCategory();
			JSONArray array = JSONArray.fromObject(categorys);// 将json字符串转成json数组

			logger.info("=========>array:" + array);
			for (int i = 0; i < array.size(); i++) {// 循环json数组
				JSONObject ob = (JSONObject) array.get(i);// 得到json对象
				logger.info("=========>ob:" + ob);

				// 放入实体
				param.setCatId(Integer.valueOf(ob.get("catId").toString()));
				param.setName(ob.get("name").toString());
				param.setParentId(Integer.valueOf(ob.get("parentId").toString()));
				logger.info("=========>ob.get(catClass).toString():" + ob.get("catClass").toString());
				if (ob.get("catClass").toString().equals("0")) {
					param.setCatClass(JDInterfaceConstant.CATEGOY_CLASS_1001);
				} else if (ob.get("catClass").toString().equals("1")) {
					param.setCatClass(JDInterfaceConstant.CATEGOY_CLASS_1002);
				} else if (ob.get("catClass").toString().equals("2")) {
					param.setCatClass(JDInterfaceConstant.CATEGOY_CLASS_1003);
				}
				if (ob.get("state").toString().equals("1")) {
					param.setState(JDInterfaceConstant.CATEGOY_TYPE_TRUE);
				} else {
					param.setState(JDInterfaceConstant.CATEGOY_TYPE_FALSE);
				}

				// 判断是否存在
				Integer catId = Integer.valueOf(ob.get("catId").toString());
				Integer ifExist = productCategoryMapper.selectIfExist(catId);
				logger.info("=========>ifExist:" + ifExist);
				if (ifExist > 0) {
					param.setUpdateDate(new Date());
					param.setUpdateBy(JDInterfaceConstant.WX_USER_ID);
					productCategoryMapper.updateCategory(param);
					logger.info("=========>更新param:" + param);
				} else {
					param.setCreateDate(new Date());
					param.setCreateBy(JDInterfaceConstant.WX_USER_ID);
					productCategoryMapper.insertCategory(param);
					logger.info("=========>插入param:" + param);
				}
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new ServiceBizException(e.getMessage(), e);
		}
		return totalRows;
	}

	/**
	 * 插入二三级规格
	 * 
	 * @param token
	 */
	public Integer insertSecondCategorys(String token, Integer pageNo, Integer catClass) {
		Integer rank = 0;
		Integer totalRows = 0;
		Integer arraySize = 0;
		try {
			if (catClass == 0) {
				rank = JDInterfaceConstant.CATEGOY_CLASS_1001;
			} else if (catClass == 1) {
				rank = JDInterfaceConstant.CATEGOY_CLASS_1001;
			} else if (catClass == 2) {
				rank = JDInterfaceConstant.CATEGOY_CLASS_1002;
			}
			List<TmTpProductCategory> categoryList = productCategoryMapper.queryParentId(rank);
			for (int j = 0; j < categoryList.size(); j++) {
				Integer parentId = categoryList.get(j).getCatId();
				String url = categoryUrl;
				// Integer pageNo=1;
				Integer pageSize = 5000;
				// Integer catClass=0;
				String params = "token=" + token + "&pageNo=" + pageNo + "&pageSize=" + pageSize + "&parentId="
						+ parentId + "&catClass=" + catClass;
				logger.info("==>params:" + params);
				String result = FrameHttpUtil.sendPost(url, params);
				logger.info("==>result:" + result);
				JSONObject data = JSONObject.fromObject(result);
				logger.info("=========>data:" + data);
				JSONObject categorysResult = data.getJSONObject("result");
				logger.info("=========>categorysResult:" + categorysResult);
				JSONArray categorys = categorysResult.getJSONArray("categorys");
				logger.info("=========>categorys:" + categorys);
				totalRows = Integer.valueOf(categorysResult.get("totalRows").toString());
				logger.info("=========>totalRows:" + totalRows);
				TmTpProductCategory param = new TmTpProductCategory();
				JSONArray array = JSONArray.fromObject(categorys);// 将json字符串转成json数组
				arraySize = array.size();
				if (arraySize != 0) {
					logger.info("=========>array:" + array);
					for (int i = 0; i < array.size(); i++) {// 循环json数组
						JSONObject ob = (JSONObject) array.get(i);// 得到json对象
						logger.info("=========>ob:" + ob);

						// 放入实体
						param.setCatId(Integer.valueOf(ob.get("catId").toString()));
						param.setName(ob.get("name").toString());
						param.setParentId(Integer.valueOf(ob.get("parentId").toString()));
						if (ob.get("catClass").toString().equals("0")) {
							param.setCatClass(JDInterfaceConstant.CATEGOY_CLASS_1001);
						} else if (ob.get("catClass").toString().equals("1")) {
							param.setCatClass(JDInterfaceConstant.CATEGOY_CLASS_1002);
						} else if (ob.get("catClass").toString().equals("2")) {
							param.setCatClass(JDInterfaceConstant.CATEGOY_CLASS_1003);
						}
						if (ob.get("state").toString().equals("1")) {
							param.setState(JDInterfaceConstant.CATEGOY_TYPE_TRUE);
						} else {
							param.setState(JDInterfaceConstant.CATEGOY_TYPE_FALSE);
						}

						// 判断是否存在
						Integer catId = Integer.valueOf(ob.get("catId").toString());
						Integer ifExist = productCategoryMapper.selectIfExist(catId);
						logger.info("=========>ifExist:" + ifExist);
						if (ifExist > 0) {
							param.setUpdateDate(new Date());
							param.setUpdateBy(JDInterfaceConstant.WX_USER_ID);
							productCategoryMapper.updateCategory(param);
							logger.info("=========>更新param:" + param);
						} else {
							param.setCreateDate(new Date());
							param.setCreateBy(JDInterfaceConstant.WX_USER_ID);
							productCategoryMapper.insertCategory(param);
							logger.info("=========>插入param:" + param);
						}
					}
				}
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new ServiceBizException(e.getMessage(), e);
		}
		return totalRows;
	}

	/**
	 * 插入规格检查分页
	 * 
	 * @param token
	 */
	public void checkCategorys(String token) {
		Integer pageNo = 1;
		Integer catClass = 0;
		Integer totalRows = 0;
		totalRows = insertCategorys(token, pageNo, catClass);
		Integer pageSize = totalRows / 5000;
		if (pageSize >= 1 && totalRows != 5000) {
			for (int i = 1; i <= pageSize; i++) {
				pageNo = pageNo + 1;
				insertCategorys(token, pageNo, catClass);
			}
		}
		catClass = 1;
		pageNo = 1;
		totalRows = insertSecondCategorys(token, pageNo, catClass);
		pageSize = totalRows / 5000;
		if (pageSize >= 1 && totalRows != 5000) {
			for (int i = 1; i <= pageSize; i++) {
				pageNo = pageNo + 1;
				insertCategorys(token, pageNo, catClass);
			}
		}
		catClass = 2;
		pageNo = 1;
		totalRows = insertSecondCategorys(token, pageNo, catClass);
		pageSize = totalRows / 5000;
		if (pageSize >= 1 && totalRows != 5000) {
			for (int i = 1; i <= pageSize; i++) {
				pageNo = pageNo + 1;
				insertCategorys(token, pageNo, catClass);
			}
		}
	}

	/**
	 * 商品可售验证接口
	 * 
	 * @param params
	 * @return
	 */
	public Map<String, Object> saleState() {
		try {
			Example example = new Example(TmTpProductPoolTemp.class);
//			Criteria criteria = example.createCriteria();
//			criteria.andCondition("sale_state=", JDInterfaceConstant.PRODUCT_POOL_1001);
			example.setOrderByClause("PAGE_NUM ASC");
			List<TmTpProductPoolTemp> poolList = productPoolTempMapper.selectByExample(example);
			BaseThread plate = new BaseThread();
			// 生产者线程
			new Thread(new AddBaseThread(plate, poolList)).start();

			// 消费者线程
			for (int i = 0; i < synchronousNum; i++) {
				new Thread(new GetSaleStateThread(plate, this)).start();
			}
			Map<String, Object> map = new HashMap<>();
			map.put("resultCode", JDInterfaceConstant.RESULTCODE_0000);
			return map;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new ServiceBizException(e.getMessage(), e);
		}
	}

	/**
	 * 商品可售验证接口
	 * 
	 * @param params
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public void querySaleState(Integer pool) {
		try {
			String token = jdInterfaceService.getToken();
			Map<String, Object> pa = new HashMap<String, Object>();

			Integer wxstate = null;
			if (synchronous) {
				wxstate = JDInterfaceConstant.WX_STATUS_UP;
			}
			pa.put("pageNum", pool);
			pa.put("wxstate", wxstate);

			List<String> list = productDetailMapper.selectAllSku(pa);
			if (list != null && list.size() > 0) {
				String arr[] = productGroupBySku(list);
				for (int i = 0; i < arr.length; i++) {
					String param = "token=" + token + "&skuIds=" + arr[i];
//					logger.info("ProductService.sellState==>params:" + param);
					String result = FrameHttpUtil.sendPost(saleStateUrl, param);
					logger.info("ProductService.sellState==>result:" + result);
					JSONObject data = JSONObject.fromObject(result);
					String resultCode = data.getString("resultCode");
					if (resultCode.equals(JDInterfaceConstant.RESULTCODE_0000)) {
						JSONArray pList = data.getJSONArray("result");
						List<ProductSaleStatePO> ppList = JSONArray.toList(pList, new ProductSaleStatePO(),
								new JsonConfig());
						for (ProductSaleStatePO pp : ppList) {
							String saleState = "";
							String isCanVAT = "";
							String is7ToReturn = "";
							if (null != pp.getSaleState()) {
								if (pp.getSaleState().equals("1")) {
									saleState = JDInterfaceConstant.PRODUCT_SALESTATE_1001.toString();
								} else if (pp.getSaleState().equals("0")) {
									saleState = JDInterfaceConstant.PRODUCT_SALESTATE_1002.toString();
								}
							}
							if (null != pp.getIsCanVAT()) {
								if (pp.getIsCanVAT().equals("1")) {
									isCanVAT = JDInterfaceConstant.PRODUCT_ISCANVAT_1001.toString();
								} else if (pp.getIsCanVAT().equals("0")) {
									isCanVAT = JDInterfaceConstant.PRODUCT_ISCANVAT_1002.toString();
								}
							}
							if (null != pp.getIs7ToReturn()) {
								if (pp.getIs7ToReturn().equals("1")) {
									is7ToReturn = JDInterfaceConstant.PRODUCT_IS7TORETURN_1001.toString();
								} else if (pp.getIs7ToReturn().equals("0")) {
									is7ToReturn = JDInterfaceConstant.PRODUCT_IS7TORETURN_1002.toString();
								}
							}
							long ty = productDetailMapper.updateProductSaleState(pp.getSkuId(), saleState, isCanVAT,
									is7ToReturn);
							if (ty == 1) {
								logger.info("ProductService.saleState==>" + pp.getSkuId() + "商品可售状态更新成功！");
							} else {
								logger.info("ProductService.saleState==>" + pp.getSkuId() + "商品可售状态更新失败！");
							}
						}
					} else {
						logger.error("ProductService.getPrice==>" + pool + "号商品池" + arr[i] + "商品可售状态获取失败！");
						logger.error("ProductService.getPrice==>error:" + data.getString("resultMessage"));
					}
				}
				TmTpProductPoolTemp productPoolTempPo = new TmTpProductPoolTemp();
				productPoolTempPo.setSaleState(JDInterfaceConstant.PRODUCT_POOL_1002);
				productPoolTempPo.setUpdateDate(new Date());
				productPoolTempPo.setUpdateBy(JDInterfaceConstant.WX_USER_ID);
				Example example1 = new Example(TmTpProductPoolTemp.class);
				Criteria criteria1 = example1.createCriteria();
				criteria1.andCondition("page_num=", pool);
				productPoolTempMapper.updateByExampleSelective(productPoolTempPo, example1);
			} else {
				TmTpProductPoolTemp productPoolTempPo = new TmTpProductPoolTemp();
				productPoolTempPo.setSaleState(JDInterfaceConstant.PRODUCT_POOL_1002);
				productPoolTempPo.setUpdateDate(new Date());
				productPoolTempPo.setUpdateBy(JDInterfaceConstant.WX_USER_ID);
				Example example1 = new Example(TmTpProductPoolTemp.class);
				Criteria criteria1 = example1.createCriteria();
				criteria1.andCondition("page_num=", pool);
				productPoolTempMapper.updateByExampleSelective(productPoolTempPo, example1);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new ServiceBizException(e.getMessage(), e);
		}
	}

	/**
	 * 商品售卖价接口
	 * 
	 * @param params
	 * @return
	 */
	public Map<String, Object> sellPrice() {
		try {
			Example example = new Example(TmTpProductPoolTemp.class);
//			Criteria criteria = example.createCriteria();
//			// 京东价和协议价格已不使用，2017-06-15起使用 商品售卖价接口，用协议价格状态字段存 售卖价状态
//			criteria.andCondition("price_state=", JDInterfaceConstant.PRODUCT_POOL_1001);
			example.setOrderByClause("PAGE_NUM ASC");
			List<TmTpProductPoolTemp> poolList = productPoolTempMapper.selectByExample(example);
			BaseThread plate = new BaseThread();
			// 生产者线程
			new Thread(new AddBaseThread(plate, poolList)).start();

			// 消费者线程
			for (int i = 0; i < synchronousNum; i++) {
				new Thread(new GetSellPriceThread(plate, this)).start();
			}
			Map<String, Object> map = new HashMap<>();
			map.put("resultCode", JDInterfaceConstant.RESULTCODE_0000);
			return map;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new ServiceBizException(e.getMessage(), e);
		}
	}

	/**
	 * 商品售卖价接口
	 * 
	 * @param params
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public void querySellPrice(Integer pool) {
		try {
			String token = jdInterfaceService.getToken();
			Map<String, Object> pa = new HashMap<String, Object>();

			Integer wxstate = null;
			if (synchronous) {
				wxstate = JDInterfaceConstant.WX_STATUS_UP;
			}
			pa.put("pageNum", pool);
			pa.put("wxstate", wxstate);

			List<String> list = productDetailMapper.selectAllSku(pa);
			if (list != null && list.size() > 0) {
				String arr[] = productGroupBySku(list);
				for (int i = 0; i < arr.length; i++) {
					String param = "token=" + token + "&sku=" + arr[i];
					logger.info("ProductService.querySellPrice==>params:" + param);
					String result = FrameHttpUtil.sendPost(sellPriceUrl, param);
					logger.info("ProductService.querySellPrice==>result:" + result);
					JSONObject data = JSONObject.fromObject(result);
					String resultCode = data.getString("resultCode");
					if (resultCode.equals(JDInterfaceConstant.RESULTCODE_0000)) {
						JSONArray pList = data.getJSONArray("result");
						List<ProductPricePO> ppList = JSONArray.toList(pList, new ProductPricePO(), new JsonConfig());
						for (ProductPricePO pp : ppList) {
							long ty = productDetailMapper.updateSellPrice(pp);
							if (ty == 1) {
								logger.info("ProductService.querySellPrice==>" + pp.getSkuId() + "商品协议价格更新成功！");
							} else {
								logger.info("ProductService.querySellPrice==>" + pp.getSkuId() + "商品协议价格更新失败！");
							}
						}
					} else {
//						logger.error("ProductService.querySellPrice==>" + pool + "号商品池" + arr[i] + "商品售卖价获取失败！");
						logger.error("ProductService.querySellPrice==>error:" + data.getString("resultMessage"));
					}
				}
				TmTpProductPoolTemp productPoolTempPo = new TmTpProductPoolTemp();
				productPoolTempPo.setPriceState(JDInterfaceConstant.PRODUCT_POOL_1002);
				productPoolTempPo.setUpdateDate(new Date());
				productPoolTempPo.setUpdateBy(JDInterfaceConstant.WX_USER_ID);
				Example example1 = new Example(TmTpProductPoolTemp.class);
				Criteria criteria1 = example1.createCriteria();
				criteria1.andCondition("page_num=", pool);
				productPoolTempMapper.updateByExampleSelective(productPoolTempPo, example1);
			} else {
				TmTpProductPoolTemp productPoolTempPo = new TmTpProductPoolTemp();
				productPoolTempPo.setPriceState(JDInterfaceConstant.PRODUCT_POOL_1002);
				productPoolTempPo.setUpdateDate(new Date());
				productPoolTempPo.setUpdateBy(JDInterfaceConstant.WX_USER_ID);
				Example example1 = new Example(TmTpProductPoolTemp.class);
				Criteria criteria1 = example1.createCriteria();
				criteria1.andCondition("page_num=", pool);
				productPoolTempMapper.updateByExampleSelective(productPoolTempPo, example1);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new ServiceBizException(e.getMessage(), e);
		}
	}
	
	/**
	 * 批量上架商品接口
	 * 
	 * @param params
	 * @return
	 */
	public Map<String, Object> productIns(List<String> list) {
		Map<String, Object> map = new HashMap<>();
		if(list!=null && !list.isEmpty()){
			for (String str : list) {
				Example example = new Example(TmTpProductDetail.class);
				Criteria criteria = example.createCriteria();
				criteria.andEqualTo("sku", str);
				TmTpProductDetail pro = new TmTpProductDetail();
				pro.setWxstate(JDInterfaceConstant.WX_STATUS_UP);
				productDetailMapper.updateByExampleSelective(pro, example);
			}
			map.put("resultCode", JDInterfaceConstant.RESULTCODE_0000);
			//商品售卖价,商品可售状态,商品上下架状态(京东状态)
			sellPrice();
			saleState();
			skuState();
		}else{
			map.put("resultCode", JDInterfaceConstant.RESULTCODE_1001);
			map.put("errMsg", "参数为空");
		}
		return map;
		
	}
}
